<?php

class sgeLdap
{

	private static $instance;

	private function __construct()
	{
	}

	public static function getInstance()
	{
		if (!self::$instance instanceof self)
			self::$instance = new self;

		return self::$instance;
	}

	public static function checkPassword($username, $password)
	{
		self::getInstance();
		$ldapcon = self::$instance->ldapConnect();
		$success = false;

		if ($ldapcon)
		{
			if (ldap_bind($ldapcon, self::$instance->getDn($username), $password))
			{
				$success = true;
			}
			ldap_unbind($ldapcon);
		}

		return $success;
	}

	public function changePassword($username, $currentPassword, $newPassword)
	{
		$dn = $this->getDn($username);
		$ldapcon = $this->ldapConnect();
		$success = false;

		if ($ldapcon)
		{
			if (ldap_bind($ldapcon, $dn, $currentPassword))
			{
				$success = ldap_mod_replace($ldapcon, $dn, array('userPassword' => '{SHA}' . base64_encode(sha1($newPassword))));
			}
			ldap_unbind($ldapcon);
		}

		return $success;
	}

	private function getDn($username)
	{
		return sprintf('cn=%s,%s', $username, sfConfig::get('sf_ldap_base_dn'));
	}

	private function ldapConnect()
	{
		$ldapcon = ldap_connect(sfConfig::get('sf_ldap_host'), sfConfig::get('sf_ldap_port'));
		ldap_set_option($ldapcon, LDAP_OPT_PROTOCOL_VERSION, 3);
		ldap_set_option($ldapcon, LDAP_OPT_REFERRALS, 0);

		return $ldapcon;
	}

	public static function getUser($login)
	{
		$instance = self::getInstance();
		$ldapcon = $instance->ldapConnect();
		$user = null;

		if ($ldapcon)
		{
			$result = ldap_search($ldapcon, sfConfig::get('sf_ldap_base_dn'), sprintf('(|(cn=%s))', $login), array('givenname', 'sn', 'mail'));
			$entry = ldap_first_entry($ldapcon, $result);

			if ($entry)
			{
				$user = new sfGuardUser();

				$attributes = ldap_get_attributes($ldapcon, $entry);

				$user->username = $login;
				$user->first_name = $instance->getAttribute($attributes, 'givenName');
				$user->last_name = $instance->getAttribute($attributes, 'sn');
				$user->email_address = $instance->getAttribute($attributes, 'mail');
			}
			ldap_unbind($ldapcon);
		}

		return $user;
	}

	private function getAttribute($attributes, $name)
	{
		if (isset($attributes[$name]))
		{
			$value = '';
			for ($i = 0; $i < $attributes[$name]['count']; $i++)
			{
				$value = $value . $attributes[$name][$i] . ' ';
			}

			return $value;
		}

		return null;
	}

}